package wxpay

import (
	"context"
	"fmt"
	"log"
	"server/global"

	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/core/option"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
)

// 获取加解密处理
func getWechatClient() (context.Context, *core.Client, error) {

	// 使用 utils 提供的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
	mchPrivateKey, err := utils.LoadPrivateKeyWithPath("apiclient/apiclient_key.pem")
	if err != nil {
		log.Printf("load merchant private key error:%s", err)
		return nil, nil, err
	}

	wechatpayPublicKey, err := utils.LoadPublicKeyWithPath("apiclient/pub_key.pem")
	if err != nil {
		panic(fmt.Errorf("load wechatpay public key err:%s", err.Error()))
	}

	ctx := context.Background()
	//// 使用商户私钥等初始化 client，并使它具有自动定时获取微信支付平台证书的能力
	//opts := []core.ClientOption{
	//	option.WithWechatPayAutoAuthCipher(global.GL_CONFIG.WxJsApi.MchID, global.GL_CONFIG.WxJsApi.MchCertificateSerialNumber, mchPrivateKey, global.GL_CONFIG.WxJsApi.MchAPIv3Key),
	//}
	opts := []core.ClientOption{
		option.WithWechatPayPublicKeyAuthCipher(
			global.GL_CONFIG.WxJsApi.MchID,
			global.GL_CONFIG.WxJsApi.MchCertificateSerialNumber, mchPrivateKey,
			global.GL_CONFIG.WxJsApi.WechatpayPublicKeyID, wechatpayPublicKey),
	}
	client, err := core.NewClient(ctx, opts...)
	if err != nil {
		log.Printf("new wechat pay client err:%s", err)
		return ctx, client, err
	}

	return ctx, client, nil
}
